#!/usr/sbin/rsct/perl5/bin/perl 
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
#  
#  
# Licensed Materials - Property of IBM 
#  
# (C) COPYRIGHT International Business Machines Corp. 1999,2002 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 
# "@(#)66   1.12   src/rsct/registry/cli/bin/rmsrfile.perl, srcli, rsct_rpyxh, rpyxht1f3 2/22/01 16:25:49"
######################################################################
#                                                                    #
# Module: rmsrfile                                                   #
#                                                                    #
# Purpose:                                                           #
#   rmsrfile - Removes files stored in System Registry tables.       #
#                                                                    #
# Syntax:                                                            #
#   rmsrfile [-h][-TV] SR_filename ...                               #
#                                                                    #
# Flags:                                                             #
#   -h Help. Writes this command's usage statement to stdout.        #
#   -T Trace. Writes this command's trace messages to stderr.        #
#   -V Verbose. Writes this command's verbose messages to stderr.    #
#                                                                    #
# Operands:                                                          #
#   SR_filename Name of the table containing the file to be removed  #
#               from the Ssystem Registry. One or more SR_filename   #
#               operand can be specified. An absolute or relative    #
#               path name can be used.                               #
#                                                                    #
# Description:                                                       #
#   The rmsrfile command allows you to remove one or more files      #
#   previously stored as tables from the System Registry. The table  #
#   matching the name SR_filename will be removed if found.          #
#                                                                    #
#   If multiple SR_filename operands are given on the command line,  #
#   this is equivalent to calling rmsrfile once for each name. An    #
#   attempt will be made to complete the command for each file given #
#   in the list, with an error reported for those files that are not #
#   able to be removed.                                              #
#                                                                    #
#   Use the lssr command to get a current listing of tables          #
#   contained in a specified System Registry directory.              #
#                                                                    #
#   You must have write permission on the directory you wish to      #
#   delete the table from.                                           #
#                                                                    #
# Exit Values:                                                       #
#   0  SR_CLI_SUCCESS        Command completed successfully.         #
#   1  SR_CLI_REGISTRY_ERROR Command terminated due to an underlying #
#                            System Registry error.                  #
#   2  SR_CLI_ERROR          Command terminated due to an underlying #
#                            error in the command script.            #
#   3  SR_CLI_BAD_OPERAND    Command terminated due to user          #
#                            specifying a bad operand.               #
#   4  SR_CLI_BAD_FLAG       Command terminated due to user          #
#                            specifying an invalid flag.             #
#   5  SR_CLI_USER_ERROR     Command terminated due to a user error. #
#                            For example specifying an undefined     #
#                            file (table) to be removed.             #
#                                                                    #
# Examples:                                                          #
#   1. To delete multiple files if the CT_SR_HOME                    #
#   environment variable is set to /samples, enter:                  #
#       rmsrfile file1 file2                                         #
#                                                                    #
#   2. To delete a single file using an absolute specification       #
#   enter:                                                           #
#       srrmtbl /samples/File3                                       #
#                                                                    #
#--------------------------------------------------------------------#
# Inputs:                                                            #
#                                                                    #
# Outputs:                                                           #
#       stdout - display of information messages                     #
#       stderr - display of error messages                           #
#                                                                    #
# External Ref:                                                      #
#   Commands: $LSMSG                                                 #
#   Extensions:  SR.pm                                               #
#   Perl library routines: Getopts::Std                              #
#   SR cli library routines: SR_cli_utils - init_session, isRelative #
#                                       term_session, printCEMsg     #
#   Environment variables:  CT_SR_HOME                               #
#                                                                    #
# Tab Settings:                                                      #
#   4 and tabs should be expanded to spaces before saving this file. #
#   in vi:  (:set ts=4  and   :%!expand -4)                          #
#                                                                    #
# Change Activity:                                                   #
#   000929 HGJ 38317: Initial delivery.                              #
#                                                                    #
######################################################################

#--------------------------------------------------------------------#
#                                                                    #
# General Progam/Logic flow for srrmtbl:                             #
#                                                                    #
#   A: Parse command line                                            #
#   B: Initialize session with registry - change current directory   #
#       based on absolute or relatvie path name given, and the       #
#       value of CT_SR_HOME, if necessary                            #
#   C: Delete table (SR_filename), using CT::SR::delete_table if it  #
#      exists in the Registry                                        #
#   D: Clean up tree used for session                                #
#                                                                    #
#--------------------------------------------------------------------#


#--------------------------------------------------------------------#
# Included Libraries and Extensions                                  #
#--------------------------------------------------------------------#
use lib "/usr/sbin/rsct/pm";
use locale;
use Getopt::Std;

use CT_cli_utils qw(printIMsg
                    printEMsg
);

use CT::SRrc;
use CT::SR;
use SR_cli_utils qw(init_session isRelative 
                    term_session printCEMsg
                    $DEFAULT_GLOBAL_MOUNT_POINT
                    error_exit  set_session_variables
);
use SR_cli_rc qw(:return_codes);


#--------------------------------------------------------------------#
# Global Variables                                                   #
#--------------------------------------------------------------------#
# Constants
$TRUE           = 1;
$FALSE          = 0;

# Other Global Variables
$Verbose        = $FALSE;               # use if -V set 
$Trace          = $FALSE;               # use if -T set

# Messaging Globals
$PROGNAME       = "rmsrfile";           # Program Name for messages
$MSGCAT         = "srcli.cat";          # msg catalogue for this cmd
$CTDIR          = "/usr/sbin/rsct";     # Cluster directory path
$CTBINDIR       = "$CTDIR/bin";         # Cluster Bin directory path
$LSMSG          = "$CTBINDIR/ctdspmsg"; # Display message routine
$ENV{'MSGMAPPATH'} = "$CTDIR/msgmaps";  # Msg map path for $LSMSG  

%Cleanup = ();                          # Hash of items to cleanup
                                        # {Session} $session to term

#--------------------------------------------------------------------#
# Variables                                                          #
#--------------------------------------------------------------------#
my @SR_filename    = ();                # Array of tables to be rmvd
my @Table          = ();                # Table names plus mount point
my $Index          = 0;
my $Mount_point    = $DEFAULT_GLOBAL_MOUNT_POINT;

my $Set_work_dir   = $FALSE;

my $rc             = 0;        
my $badrc          = 0;


#--------------------------------------------------------------------#
# Main Code                                                          #
#--------------------------------------------------------------------#
# TODO: Many verbose statements in this code will eventually by
# Trace statements when the facility is available as a Perl CLI
# (feature 48401)
# TODO: security on access to the table can not be further defined
# until after a security design has been implemented for the SR.
# ( feature 48402 ) Until then, the table is opened with the
# minimum security necessary to complete the command.


# Parse the command line, exit if there are errors
($rc, @SR_filename) = parse_cmd_line();
($rc == 0) || error_exit($rc);

if ($Verbose) {
    foreach (@SR_filename) { $Command_line_input .= $_; }
    $Command_line_input = '"'.$Command_line_input.'"';
    printIMsg("IMsgrmsrfileCommandLineInput", $Command_line_input);
}


# Initialize variables for initSession - check to see if an
# absolute or relative table name has been passed in.
# Add the mount point to each absolute table so it can be
# handled by the System Registry.

foreach (@SR_filename) {
    ($holder, $Table[$Index++]) = set_session_variables($_);
    if ($holder == $TRUE) {$Set_work_dir = $TRUE;}
}


# Initialize session with registry; set current directory
# If one of the tables requires the current working directory to
# be set, then it is set. (Determined in the previous foreach loop)

($rc, $Tree_handle) = init_session( $Set_work_dir );
($rc == 0) || error_exit($rc);

# Add tree handle to cleanup hash
$Cleanup{Session} = $Tree_handle;


# Attempt to delete each table in the list. Report an error if 
# necessary, keep the highest error code to return
foreach (@Table) {
    $Verbose && printIMsg("IMsgrmsrfileRemovingFile", $_);

    # Call C API to delete the table 
    $Trace && print STDERR "Calling CT::SR::delete_table($_)\n";
    $rc = CT::SR::delete_table($Tree_handle, $_);
    $Trace && print STDERR "CT::SR::delete_table return code: $rc\n";

    $rc = error_check("sr_delete_table", $rc, $_);
    if ($rc == SR_CLI_REGISTRY_ERROR) {
        $badrc = $rc;
        last;
    }
    # Save the first bad return code 
    if ($rc != 0 && $badrc == 0) { $badrc = $rc; }
}
($badrc == 0) || error_exit($badrc);

# Continue and try to exit gracefully from the session
$rc = term_session($Tree_handle, $Mount_point);

exit $rc;

#--------------------------------------------------------------------#
# End Main Code                                                      #
#--------------------------------------------------------------------#


#--------------------------------------------------------------------#
# parse_cmd_line:                                                    #
#   Uses getopts() to grab flags on the command line, then grabs     #
#   and returns all table names provided for deletion.               #
#                                                                    #
# Return values:                                                     #
#   $local_rc   - return code.                                       #
#   @table_name - array of tables names to be deleted.               #
#                                                                    #
# Global variables modified:                                         #
#   $Trace             output   True (-T) turn Trace mode on.        #
#   $Verbose           output   True (-V) turn Verbose mode on.      #
#--------------------------------------------------------------------#
sub parse_cmd_line
{
my $local_rc = 0;
my @table_name = ();
my $index = 0;
my %opts = ();
    
if (getopts('hTV', \%opts) == 0) {   # parse input flags  
    printCEMsg("EMsgSRcliInvalidFlag");
    print_usage();  
    return SR_CLI_BAD_FLAG;      
}

if (defined $opts{h}) {          # print usage and exit
    print_usage();   
    exit(0);
}

# Set Trace flag if requested,
if (defined $opts{T}) {
    $Trace = $TRUE;     
}

# Set Verbose flag if requested.
if (defined $opts{V}) {
    $Verbose = $TRUE;     
}

# Grab the table name(s) from the command line or report an error
# if there aren't any.
if (@ARGV) {
    # Load the output array with tables to be processed.
    while (@ARGV) { 
        $table_name[$index++] = shift @ARGV;
    }
}
else {
    printCEMsg("EMsgSRcliFileNameMissing");
    print_usage();
    return SR_CLI_BAD_OPERAND;
}

return ($local_rc, @table_name); 
}   # end parse_cmd_line


#--------------------------------------------------------------------#
# error_check:                                                       #
#   Checks the return code from the SR function.  If an error is     #
#   detected appropriate error messages will be displayed and        #
#   SR CLI return code set.                                          #
#                                                                    #
# Parameters:                                                        #
#   $sr_function  - Name of the SR function that was called and      #
#                   whose error code we are checking.                #
#   $sr_rc        - SR function return code.                         #
#   $table_name   - Name of the table/file trying to delete.         #
#                                                                    #
# Return values:                                                     #
#   None.                                                            #
#                                                                    #
# Global References:                                                 #
#   None.                                                            #
#--------------------------------------------------------------------#
sub error_check
{
my ($sr_function, $sr_rc, $table_name) = @_;
my $rc = 0;

if ($sr_rc != 0) {
    if ($sr_rc == SR_NO_PERMISSION) {
        printEMsg("EMsgrmsrfileNoPermission", $table_name);
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_NO_TABLE) {
        printEMsg("EMsgrmsrfileNoTable", $table_name);
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_TABLE_LOCKED) {
        printEMsg("EMsgrmsrfileTableLocked", $table_name);
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_CONNECTION_LOST) {
        printCEMsg("EMsgSRcliConnectionLost");
        $rc = SR_CLI_REGISTRY_ERROR;
    }
    else {
        printEMsg("EMsgrmsrfileErrorRemovingFile ", $_, $rc); 
        printCEMsg("EMsgSRcliSRCommandFailure", $sr_function, $sr_rc);
        $rc = SR_CLI_REGISTRY_ERROR;        
    }
}

return ($rc);
}   # end error_check


#--------------------------------------------------------------------#
# print_usage : print the usage statement (syntax) to stdout.        #
#   See this command's prologue syntax section for current usage.    #
#--------------------------------------------------------------------#
sub print_usage
{
printIMsg("IMsgrmsrfileUsage");
}   # end print_usage


#--------------------------------------------------------------------#
# End File                                                           #
#--------------------------------------------------------------------#
